/**
 * Created by Administrator on 2018/7/3.
 */
//存放权限 是否 选择
$$scope.role = {};
$$scope.autho = { projId: proId };
$$scope.autho.projId = proId;
$$scope.autho.authority = {};
//存放 权限 是否 被 注销
$$scope.autho.originValue = {};
$$scope.autho.baseInfo = { roleId: "" };
$$scope.autho.baseInfo.userId = "";
$$scope.autho.baseInfo.userName = "";
$$scope.autho.baseInfo.projId = proId;
$$scope.autho.baseInfo.descriptor = "";
//角色 可能 存在 兼岗
$$scope.autho.baseInfo.role = "";
var staffColumns = [{
    id: 'userName',
    title: '人员姓名',
    width: 75,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'positonName',
    title: '岗位名称',
    // width: 100,
    type: 'string',
    columnClass: 'text-center',
}, {
    id: 'createTime',
    title: '入职时间',
    type: 'string',
    width: 150,
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var date = new Date(record.createTime);
        var content = $.fn.dlshouwen.grid.tools.dateFormat(date, "yyyy-MM-dd hh:mm");
        return content;
    }
}, {
    id: 'operation',
    title: '操作',
    width: 70,
    type: 'string',
    columnClass: 'text-center',
    resolution: function (value, record, column, grid, dataNo, columnNo) {
        var content = '';
        content += '<button class="btn btn-xs btn-success" onclick="select(\'' + record.userName + '\',\'' + record.userId + '\',\'' + record.positonName + '\');"><i class="icon-ok"></i>  选择</button>';
        return content;
    }
}];
$CertusFormAjax.ajax("findRelatedRole", { projectType: projectType, projId: proId }, function (res) {

    $$scope.roles = res.data;
})
// $CertusJsonAjax.dataInit("userList", null, staffColumns, 'userDataGird', 'userGridToolBarContainer')

$(".searchButtom").on("click", function () {
    $("#userDataGird").empty();
    $("#userGridToolBarContainer").empty();
    if ($("#searchInputId").val() == "") {
        // $CertusJsonAjax.dataInit("userList", null, staffColumns, 'userDataGird', 'userGridToolBarContainer');
        $('#userDataGird').removeClass('n-pt-15');
        layer.msg("请输入....");
        return;
    }
    $CertusJsonAjax.dataInit("searchCompany", { "param": $("#searchInputId").val() }, staffColumns, 'userDataGird', 'userGridToolBarContainer', 5)
    $('#userDataGird').addClass('n-pt-15');
});

/*初始化 权限 列表*/
$CertusFormAjax.ajax("queryProjAuthoriy", { projectType: projectType, projId: proId }, function (res) {

    $$scope.baseAuthoritys = res.data;
})

function select(a, b, c) {
    $$scope.autho.baseInfo.userId = b;
    $$scope.autho.baseInfo.userName = a;
    $CertusFormAjax.ajax("existedUser", { userId: b, projId: proId }, function (res) {
        if (res.data == "yes") {
            layer.msg("该成员已经存在，继续添加将覆盖原有数据");
        }
    })
    $("#staffInputId").val(a + "(" + b + ")" + "--" + c);
    $(".pdmiddle").hide();
}

/*权限选择框 变化 调用函数*/
$$scope.createChangeFunc = function ($event, a) {
    var code = $($event.target).attr("authorityCode");
    $$scope.autho.authority[code] = a;
    nowOriginVlaue(code, 'user');
    // if (!a) {
    //     var code1 = code.split("-")[0]
    //     $$scope.autho.authority[code1] = a;
    // }
}

/*权限选择框  全选按钮*/
$$scope.allChangeFunc = function ($event, a) {
    var code = $($event.target).attr("authorityCode");
    //create
    var screate = code + "-create";
    $$scope.autho.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
    //retrieve
    var screate = code + "-retrieve";
    $$scope.autho.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
    //update
    var screate = code + "-update";
    $$scope.autho.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
    //delete
    var screate = code + "-delete";
    $$scope.autho.authority[screate] = a;
    nowOriginVlaue(screate, 'user');
}

/*角色选择框 调用*/
$$scope.roleSelectedChange = function ($event, a, roleName) {
    ;
    if (a) {
        var roleId = $($event.target).attr("roleId");
        $("#roleInputId").val($("#roleInputId").val() + "," + roleName);
        $$scope.autho.baseInfo.roleId += "," + roleId + ",";
        $$scope.autho.baseInfo.roleName = $("#roleInputId").val();
        var regEx = /,+/g;
        $("#roleInputId").val($("#roleInputId").val().replace(regEx, ","));
        $CertusFormAjax.ajax("pitchAuthority", { roleId: roleId, projId: proId }, function (res) {
            if (res.data) {
                for (var index in res.data) {
                    $$scope.autho.authority[index] = true;
                    nowOriginVlaueRole(index, "role");
                }
            }
        })
    } else {
        var roleId = $($event.target).attr("roleId");
        $$scope.autho.baseInfo.roleId = $$scope.autho.baseInfo.roleId.replace(roleId, "");
        $("#roleInputId").val($("#roleInputId").val().replace(roleName, ""));
        var regEx = /,/g;
        $("#roleInputId").val($("#roleInputId").val().replace(regEx, ","));

        $CertusFormAjax.ajax("pitchAuthority", { roleId: roleId, projId: proId }, function (res) {
            if (res.data) {
                for (var index in res.data) {
                    $$scope.autho.authority[index] = false;
                    nowOriginVlaueRole(index, "null");
                }
            }
        })
    }
    if ($("#roleInputId").val().indexOf(",") == 0) {
        $("#roleInputId").val($("#roleInputId").val().replace(",", ""))
    }
    while ($("#roleInputId").val().length && $("#roleInputId").val().lastIndexOf(",") == $("#roleInputId").val().length - 1 && $("#roleInputId").val().length > 1) {
        $("#roleInputId").val($("#roleInputId").val().substring(0, $("#roleInputId").val().length - 1))
    }
    $$scope.autho.baseInfo.roleName = $("#roleInputId").val();
}

/*保存 按钮 调用方法*/
$$scope.saveProjectAuthority = function () {
    if (certusValidateNotnull()) {

        var reg = /\d+/;
        if ($$scope.autho.baseInfo.roleId) {
            if (!reg.test($$scope.autho.baseInfo.roleId)) {
                layer.msg("请添加至少一个，角色");
                return;
            }
            if ($$scope.autho.baseInfo.roleId.length > 200) {
                layer.msg("请不要 添加太多的角色");
                return;
            }
        }else{
            layer.msg("请添加至少一个，角色");
            return;
        }

        $CertusJsonAjax.ajax("saveProjAuthority", $$scope.autho, function (res) {
            if ("success" == res.data) {
                $$scope.autho.operate = "new";
                $CertusJsonAjax.ajaxNode("member", "projUserOperate", $$scope.autho, function (res) {
                    //刷新 操作记录 变更
                    layer.msg(res);
                })
                layer.msg("保存成功");
                disProStaffAndEidtAuthority();
            } else {
                layer.msg(res.data);
            }
        })
    }
}

/*utils 函数 */
function nowOriginVlaue(s, roleOrUser) {
    var ss = s + "-origin";
    var snow = s + "-now";
    if ($$scope.autho.originValue[ss] == "" || $$scope.autho.originValue[ss] == "null" || angular.isUndefined($$scope.autho.originValue[ss])) {
        $$scope.autho.originValue[ss] = roleOrUser;
        $$scope.autho.originValue[snow] = roleOrUser;
    } else {
        $$scope.autho.originValue[snow] = roleOrUser;
    }
}

function nowOriginVlaueRole(s, roleOrUser) {
    var ss = s + "-origin";
    var snow = s + "-now";
    $$scope.autho.originValue[ss] = roleOrUser;
    $$scope.autho.originValue[snow] = roleOrUser;
}


// 成员权限
// 员工姓名-客户自动补全
$CertusFormAjax.ajax("findSpUserList", {}, function (response) {
    var nhlTeams = [];
    var data = response.data;
    for (var i = 0; i < data.length; i++) {
        var arr = {};
        arr.name = data[i].userName + "[" + data[i].positonName + "]";
        arr.id = data[i].userId;
        arr.userName = data[i].userName;
        nhlTeams.push(arr);
    }
    //自动补全
    var nhl = $.map(nhlTeams, function (obj) {
        return {
            value: obj.name,
            data: { category: obj.id,userName: obj.userName}
        };
    });
    // Initialize autocomplete with local lookup:
    $('#empName').devbridgeAutocomplete({
        lookup: nhl,
        minChars: 1,
        onSelect: function (suggestion) {
            $("#empId").val(suggestion.data.category);
            $("#userName").val(suggestion.data.userName);
            $$scope.autho.baseInfo.userId = suggestion.data.category;
            $$scope.autho.baseInfo.userName = suggestion.data.userName;
        },
        showNoSuggestionNotice: true,
        noSuggestionNotice: 'Sorry, no matching results'
    });
});